App.directive('edKeditor', [function () {

    var linkFn = function (scope, elm, attr, ctrl) {

        if (typeof KindEditor === 'undefined') {
            console.error('Please import the local resources of kindeditor!');
            return;
        }

        var _config = {
            resizeType: 1,
            //minWidth: '250px',
            allowPreviewEmoticons: false,
            allowImageUpload: false,
            items: [
                'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
                'insertunorderedlist', '|', 'emoticons', 'image', 'link'],
            autoHeightMode: false,
            afterCreate: function () {
                this.loadPlugin('autoheight');
            }
        };

        var editorId = elm[0], editorConfig = _config;
        angular.extend(editorConfig, scope[attr.edKeditor]);

        editorConfig.afterChange = function () {
            //if (!scope.$$phase) {
            ctrl.$setViewValue(this.html());
            // exception happens here when angular is 1.2.28
            // scope.$apply();
            //}
        };

        var editor;

        if (KindEditor) {
            editor = KindEditor.create(editorId, editorConfig);
        }

        ctrl.$parsers.push(function (viewValue) {
            ctrl.$setValidity('keditor', viewValue);
            return viewValue;
        });
        ctrl.$render = function() {
            editor.html(ctrl.$viewValue || '');
        }
    };

    return {
        require: 'ngModel',
        scope: {
            model : '@ngModel'
        },
        //scope: { config: '=config' },
        link: linkFn
    };
}]);